package com.shuiqinling.ww.android.cn00.wxapi;

import java.io.IOException;
import java.util.HashMap;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;

import com.shuiqinling.ww.android.AndroidDirectCall;
import com.shuiqinling.ww.android.Util.HttpUtil;
import com.shuiqinling.ww.android.Util.HttpUtil.HttpCallback;
import com.shuiqinling.ww.android.Util.UIHelper;
import com.tencent.mm.sdk.constants.ConstantsAPI;
import com.tencent.mm.sdk.modelbase.BaseReq;
import com.tencent.mm.sdk.modelbase.BaseResp;
import com.tencent.mm.sdk.modelbase.BaseResp.ErrCode;
import com.tencent.mm.sdk.modelmsg.SendAuth;
import com.tencent.mm.sdk.modelmsg.SendAuth.Resp;
import com.tencent.mm.sdk.modelmsg.WXMediaMessage;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.IWXAPIEventHandler;

public class WXEntryActivity extends  Activity implements IWXAPIEventHandler {

	private static final String TAG = "WXLOGIN";
	private IWXAPI api;

	public static String APP_ID_FOR_LOGIN = "";
	public static String APP_SECRET_FOR_LOGIN = "";

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		api = WeChat.api;
		api.handleIntent(getIntent(), this);
	}

	@Override
	protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);
		setIntent(intent);
		api.handleIntent(intent, this);
	}

	@Override
	public void onReq(BaseReq arg0) {

	}

	@Override
	public void onResp(BaseResp resp) {
		if (resp.getType() == ConstantsAPI.COMMAND_SENDAUTH) {
			SendAuth.Resp authResp = (Resp) resp;
			switch (authResp.errCode) {
			case ErrCode.ERR_OK:
				UIHelper.ShowToast("WXCODE:" + authResp.code + "!!!!!", 0);
				getAccessToken(authResp.code);
				break;
			case ErrCode.ERR_USER_CANCEL:
			case ErrCode.ERR_AUTH_DENIED:
				UIHelper.ShowToast("用户取消微信登录");
				HashMap<String, String> paramData = new HashMap<String, String>();
				paramData.put("status", "1");
				AndroidDirectCall.SendMessageToUnity(TAG, paramData);
				break;
			}
		}
		this.finish();
	}

	private void getAccessToken(String code) {
		final String accessTokeRequestUrl = "https://api.weixin.qq.com/sns/oauth2/access_token";

		final HashMap<String, Object> requestParamsMap = new HashMap<String, Object>();
		requestParamsMap.put("appid", WXEntryActivity.APP_ID_FOR_LOGIN);
		requestParamsMap.put("secret", WXEntryActivity.APP_SECRET_FOR_LOGIN);
		requestParamsMap.put("code", code);
		requestParamsMap.put("grant_type", "authorization_code");

		final HttpCallback httpCallback = new HttpCallback() {

			@Override
			public void OnHttpResponse(int ResponceCode, String content) {
				UIHelper.ShowToast(ResponceCode + "_" + content, 0);
				if (ResponceCode == 200) {
					parseAccessTokenMessage(content);
				} else {
					wx_login_error();
				}
			}
		};

		Runnable runnable = new Runnable() {
			public void run() {
				try {
					HttpUtil.DoPost(accessTokeRequestUrl, requestParamsMap, httpCallback);
				} catch (IOException e) {
					e.printStackTrace();
				}

			}
		};

		new Thread(runnable).start();
	}

	private void getUserInfo() {
		final String getUserInfoRequestUrl = "https://api.weixin.qq.com/sns/userinfo";

		final HashMap<String, Object> requestParamsMap = new HashMap<String, Object>();
		requestParamsMap.put("appid", WXEntryActivity.APP_ID_FOR_LOGIN);
		requestParamsMap.put("access_token", access_token);
		requestParamsMap.put("openid", openID);

		final HttpCallback httpCallback = new HttpCallback() {

			@Override
			public void OnHttpResponse(int ResponceCode, String content) {
				UIHelper.ShowToast(ResponceCode + "_" + content,0);
				if (ResponceCode == 200) {
					parseUserInfoMessage(content);
				} else {
					wx_login_error();
				}
			}
		};

		Runnable runnable = new Runnable() {
			public void run() {
				try {
					HttpUtil.DoPost(getUserInfoRequestUrl, requestParamsMap, httpCallback);
				} catch (IOException e) {
					e.printStackTrace();
				}

			}
		};

		new Thread(runnable).start();
	}

	private String openID;
	private String access_token;
	private String expires_in;
	private String unionId;

	protected void parseAccessTokenMessage(String content) {
		try {
			JSONObject json = new JSONObject(content);
			openID = json.getString("openid");
			access_token = json.getString("access_token");
			expires_in = json.getString("expires_in");
			unionId = json.getString("unionid");
			getUserInfo();
		} catch (JSONException e) {
			e.printStackTrace();
			wx_login_error();
		}
	}

	protected void parseUserInfoMessage(String content) {
		try {
			JSONObject json = new JSONObject(content);

			UIHelper.ShowToast("微信登录成功");
			HashMap<String, String> paramData = new HashMap<String, String>();
			paramData.put("status", "0");
			paramData.put("openid", openID);
			paramData.put("access_token", access_token);
			paramData.put("expires_in", expires_in);
			paramData.put("nickname", json.getString("nickname"));
			paramData.put("unionid", unionId);

			AndroidDirectCall.SendMessageToUnity(TAG, paramData);
		} catch (JSONException e) {
			e.printStackTrace();
			wx_login_error();
		}
	}

	private void wx_login_error() {
		UIHelper.ShowToast("微信登录失败");
		HashMap<String, String> paramData = new HashMap<String, String>();
		paramData.put("status", "2");
		AndroidDirectCall.SendMessageToUnity(TAG, paramData);
	}

	// /for ShareSDK

	public void onGetMessageFromWXReq(final WXMediaMessage msg) {
		if (msg != null) {
			final Intent iLaunchMyself = this.getPackageManager().getLaunchIntentForPackage(this.getPackageName());
			this.startActivity(iLaunchMyself);
		}
	}

	public void onShowMessageFromWXReq(final WXMediaMessage msg) {
//		if (msg != null && msg.mediaObject != null && msg.mediaObject instanceof WXAppExtendObject) {
//			final WXAppExtendObject obj = (WXAppExtendObject) msg.mediaObject;
//			String str=((CharSequence) obj.extInfo).toString();
//			UIHelper.ShowToast(str, 0);
//		}
	}

	// /for ShareSDK end

}
